package com.example.concurrent.demo.runnable;

import java.text.SimpleDateFormat;
import java.util.Random;

/**
 * @author susc
 * @title: ThreadLocalExample
 * @projectName concurrent-demo
 * @description: TODO
 * @date 2021/9/2814:37
 */
public class ThreadLocalExample implements Runnable{

    // SimpleDateFormat 不是线程安全的，所以每个线程都要有自己的独立副本
    private static final ThreadLocal<SimpleDateFormat> formatter = ThreadLocal.withInitial(()-> new SimpleDateFormat("yyyyMMdd HHmm"));
    private static final ThreadLocal<SimpleDateFormat> formatter2 = ThreadLocal.withInitial(()-> new SimpleDateFormat("yyyyMMdd HHmm"));

    @Override
    public void run() {
        String threadInfo = "Thread Name= " + Thread.currentThread().getName() + " default Formatter = " + formatter.get().toPattern();
        System.out.println(threadInfo);
        try {
            // 获取ThreadLocalMap数据
            Thread.sleep(new Random().nextInt(1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // formatter pattern is changed here by thread,but it won't reflect to other threads
        formatter.set(new SimpleDateFormat());
        String threadInfo2 = "Thread Name= " + Thread.currentThread().getName() + " default Formatter = " + formatter.get().toPattern();
        System.out.println(threadInfo2);
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadLocalExample example = new ThreadLocalExample();
        for(int i=0;i<10;i++){
            Thread t = new Thread(example, ""+ i);
            Thread.sleep(new Random().nextInt(1000));
            t.start();
        }
    }
}
